package com.ophiux.wechat.oauth;

import com.ophiux.wechat.utils.CommonUtil;

import net.sf.json.JSONObject;


public class OauthUtil {

	/**
	 * 微信授权获取openid地址
	 */
	private static String OAUTH_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
			"appid=APP_ID&secret=APP_SECRET&code=CODE&grant_type=authorization_code";
	
	/**
	 * 获取openID
	 */
	public static String getWxOpenID(String appid,String appsecret,String code){
		
		String url = OAUTH_URL.replace("APP_ID",appid)
				.replace("APP_SECRET", appsecret).replace("CODE", code);
		
		String tempValue="";
		String openId = "";
		String oauResp = "";
		try {
			 oauResp = CommonUtil.httpsRequest(OAUTH_URL, CommonUtil.HTTP_GET, "");		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JSONObject  jsonObj = JSONObject.fromObject(oauResp);
		if(jsonObj.containsKey("errcode")){
			//授权出错
			System.out.println(tempValue);
			openId = "";
		}
		openId = jsonObj.getString("openid");
		
		return openId;
		
	}
	
}
